// 检查 Vue 是否存在
if (typeof Vue === 'undefined') {
    console.error('Vue is not loaded!');
} else {
    console.log('Vue version:', Vue.version);
}

const { createApp } = Vue;

// 检查 createApp 是否可用
if (typeof createApp !== 'function') {
    console.error('Vue createApp is not available!');
}

createApp({
    created() {
        console.log('Vue instance created');
    },
    data() {
        return {
            formData: {
                id: null,
                name: '',
                category_id: '',
                pictures_count: 1,
                sample_data: '',
                input_fields: [],
                price: 0,
                regex: '',
                template_data: '',
                switch_reasons: [],
                user_task_limit: 0,
                duration: 3600, // 默认1小时
                is_open: '1', // 默认开启
            },
            categories: [], // 存储分类列表
            isEdit: false,
            testData: 'goods_id=123456&shop_name=测试店铺',
            editor: null
        }
    },
    computed: {
        // 修改正则匹配结果计算属性，确保始终返回数组
        regexMatches() {
            if (!this.formData?.regex || !this.testData) return [];
            try {
                const regex = new RegExp(this.formData.regex);
                const match = this.testData.match(regex);
                // 确保返回值是数组
                return Array.isArray(match) ? match : [];
            } catch (error) {
                console.error('正则表达式错误:', error);
                return [];
            }
        },
        
        // 修改预览内容计算属性
        previewContent() {
            if (!this.formData?.template_data) return '';
            
            try {
                // 先替换占位符
                let result = this.formData.template_data;
                if (Array.isArray(this.regexMatches) && this.regexMatches.length > 1) {
                    for (let i = 1; i < this.regexMatches.length; i++) {
                        const placeholder = new RegExp('\\{' + (i-1) + '\\}', 'g');
                        result = result.replace(placeholder, this.regexMatches[i] || '');
                    }
                }

                // 处理换行
                result = result.split('\n').map(line => `<p class="template-line">${line}</p>`).join('');

                // 处理特殊标签
                // 处理跳转链接
                result = result.replace(/<jmp>(.*?)<\/jmp>/g, (match, url) => {
                    return `<a href="${url}" class="template-btn template-link" target="_blank">跳转</a>`;
                });

                // 处理复制按钮 - 修改为和跳转按钮一样的样式
                result = result.replace(/<copy>(.*?)<\/copy>/g, (match, text) => {
                    return `<button class="template-btn template-copy" data-copy="${text}">复制</button>`;
                });

                return result;
            } catch (error) {
                console.error('模板渲染错误:', error);
                return '模板渲染失败';
            }
        }
    },
    methods: {
        initEditor() {
            // 简化工具栏选项
            const toolbarOptions = [
                [{ 'header': [1, 2, 3, false] }],
                ['bold', 'italic', 'underline'],
                [{ 'align': [] }],
                ['image']
            ];

            // 自定义容器类名
            const container = document.getElementById('editor');
            container.classList.add('mobile-editor');

            this.editor = new Quill('#editor', {
                modules: {
                    toolbar: {
                        container: toolbarOptions,
                        handlers: {
                            'image': () => this.handleImageUpload()
                        }
                    }
                },
                theme: 'snow',
                placeholder: '请输入示例内容...'
            });

            // 监听编辑器内容变化
            this.editor.on('text-change', () => {
                this.formData.sample_data = this.editor.root.innerHTML;
            });
        },
        // 添加图片压缩方法
        async compressImage(file, maxWidth = 1024, quality = 0.8) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = (e) => {
                    const img = new Image();
                    img.src = e.target.result;
                    img.onload = () => {
                        const canvas = document.createElement('canvas');
                        let width = img.width;
                        let height = img.height;

                        // 如果图片宽度超过最大宽度，等比例缩放
                        if (width > maxWidth) {
                            height = Math.round((height * maxWidth) / width);
                            width = maxWidth;
                        }

                        canvas.width = width;
                        canvas.height = height;

                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0, width, height);

                        // 转换为 blob
                        canvas.toBlob((blob) => {
                            if (!blob) {
                                reject(new Error('图片压缩失败'));
                                return;
                            }
                            
                            // 创建新的文件对象
                            const compressedFile = new File([blob], file.name, {
                                type: 'image/jpeg',
                                lastModified: Date.now()
                            });

                            console.log('压缩前后对比：', {
                                beforeSize: (file.size / 1024).toFixed(2) + 'KB',
                                afterSize: (compressedFile.size / 1024).toFixed(2) + 'KB'
                            });

                            resolve(compressedFile);
                        }, 'image/jpeg', quality);
                    };
                    img.onerror = (error) => reject(error);
                };
                reader.onerror = (error) => reject(error);
            });
        },
        // 修改图片上传处理方法
        async handleImageUpload() {
            const input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.click();

            input.onchange = async () => {
                const file = input.files[0];
                if (file) {
                    try {
                        // 在发送请求前检查文件
                        if (file.size <= 0) {
                            throw new Error('文件内容无效');
                        }

                        // 显示上传中提示
                        const loadingToast = Swal.fire({
                            title: '处理中...',
                            text: '正在压缩图片...',
                            allowOutsideClick: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });

                        // 压缩图片
                        const compressedFile = await this.compressImage(file);
                        
                        console.log('File details:', {
                            name: compressedFile.name,
                            type: compressedFile.type,
                            size: compressedFile.size
                        });

                        // 创建 FormData 对象上传图片
                        const formData = new FormData();
                        formData.append('image', compressedFile);

                        loadingToast.update({ text: '正在上传...' });

                        // 调用图片上传API
                        const response = await fetch('/api/admin/upload', {
                            method: 'POST',
                            body: formData
                        });

                        const data = await response.json();
                        loadingToast.close();

                        if (data.code === 200) {
                            // 获取图片URL并插入编辑器
                            const imageUrl = data.data.url;
                            const range = this.editor.getSelection(true);
                            this.editor.insertEmbed(range.index, 'image', imageUrl);
                        } else {
                            throw new Error(data.msg || '上传失败');
                        }
                    } catch (error) {
                        console.error('图片上传失败:', error);
                        Swal.fire({
                            icon: 'error',
                            title: '上传失败',
                            text: error.message || '请重试'
                        });
                    }
                }
            };
        },
        addInputField() {
            this.formData.input_fields.push({
                name: '',
                value: '',
                show_field: true // 默认显示
            });
        },
        removeInputField(index) {
            this.formData.input_fields.splice(index, 1);
        },
        async loadCategories() {
            try {
                const response = await fetch('/api/admin/categories/all');
                const data = await response.json();
                if (data.code === 200) {
                    this.categories = data.data;
                }
            } catch (error) {
                console.error('加载分类列表失败:', error);
            }
        },
        async initTemplate() {
            const urlParams = new URLSearchParams(window.location.search);
            const templateId = urlParams.get('id');
            
            if (templateId) {
                this.isEdit = true;
                this.formData.id = templateId;
                
                try {
                    const response = await fetch(`/api/admin/template?id=${templateId}`);
                    const data = await response.json();
                    
                    if (data.code === 200) {
                        // 填充表单数据
                        this.formData = {
                            ...this.formData,
                            ...data.data,
                            id: templateId,
                            // 确保 switch_reasons 是数组
                            switch_reasons: data.data.switch_reasons ? 
                                JSON.parse(data.data.switch_reasons) : [],
                            // 确保 user_task_limit 是数字
                            user_task_limit: data.data.user_task_limit || 0,
                            // 确保 duration 是数字
                            duration: data.data.duration || 3600,
                            category_id: data.data.category_id || ''
                        };
                        
                        // 如果有输入结构，解析JSON
                        if (data.data.input_structure) {
                            this.formData.input_fields = JSON.parse(data.data.input_structure);
                        }
                        
                        // 更新编辑器内容
                        if (this.editor && data.data.sample_data) {
                            this.editor.root.innerHTML = data.data.sample_data;
                        }
                    } else {
                        throw new Error(data.msg || '获取模板数据失败');
                    }
                } catch (error) {
                    console.error('获取模板数据失败:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '获取模板数据失败',
                        text: error.message || '请重试'
                    });
                }
            }
        },
        async handleSubmit() {
            try {
                // 表单验证
                if (!this.formData.name?.trim()) {
                    Swal.fire({
                        icon: 'warning',
                        title: '请填写模板名称'
                    });
                    return;
                }


                // 检查输入框结构是否填写完整
                const hasEmptyField = this.formData.input_fields.some(field => 
                    !field.name?.trim()
                );
                if (hasEmptyField) {
                    Swal.fire({
                        icon: 'warning',
                        title: '请完善输入框结构',
                        text: '输入框名称不能为空'
                    });
                    return;
                }

                // 检查并上传示例数据中的base64图片
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = this.formData.sample_data;
                const images = tempDiv.getElementsByTagName('img');
                let hasBase64Image = false;

                // 显示上传中提示
                const loadingToast = Swal.fire({
                    title: '处理中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // 处理所有图片
                for (let img of images) {
                    const src = img.getAttribute('src');
                    if (src.startsWith('data:image')) {
                        hasBase64Image = true;
                        try {
                            // 将base64转换为文件并压缩
                            const response = await fetch(src);
                            const blob = await response.blob();
                            const file = new File([blob], 'image.png', { type: 'image/png' });
                            
                            // 压缩图片
                            const compressedFile = await this.compressImage(file);

                            // 上传图片
                            const formData = new FormData();
                            formData.append('image', compressedFile);

                            const uploadResponse = await fetch('/api/admin/upload', {
                                method: 'POST',
                                body: formData
                            });

                            const uploadData = await uploadResponse.json();
                            if (uploadData.code === 200) {
                                // 替换base64为服务器URL
                                img.setAttribute('src', uploadData.data.url);
                            } else {
                                throw new Error(uploadData.msg || '图片上传失败');
                            }
                        } catch (error) {
                            loadingToast.close();
                            Swal.fire({
                                icon: 'error',
                                title: '图片处理失败',
                                text: error.message || '请重试'
                            });
                            return;
                        }
                    }
                }

                // 如果有图片被处理，更新sample_data
                if (hasBase64Image) {
                    this.formData.sample_data = tempDiv.innerHTML;
                }

                // 验证切换原因
                const hasEmptyReason = this.formData.switch_reasons.some(reason => 
                    !reason.text?.trim()
                );
                if (hasEmptyReason) {
                    Swal.fire({
                        icon: 'warning',
                        title: '请完善切换原因',
                        text: '切换原因不能为空'
                    });
                    return;
                }

                // 构建提交数据
                const submitData = {
                    id: this.formData.id,
                    name: this.formData.name.trim(),
                    pictures_count: this.formData.pictures_count,
                    sample_data: this.formData.sample_data,
                    input_structure: JSON.stringify(this.formData.input_fields.map(field => ({
                        name: field.name.trim(),
                        value: field.value?.trim() || '',
                        show_field: field.show_field
                    }))),
                    switch_reasons: JSON.stringify(this.formData.switch_reasons),
                    price: this.formData.price,
                    regex: this.formData.regex,
                    template_data: this.formData.template_data,
                    user_task_limit: parseInt(this.formData.user_task_limit) || 0,
                    duration: parseInt(this.formData.duration) || 3600,
                    is_open: this.formData.is_open,
                    category_id: this.formData.category_id
                };
    

                // 根据是否是编辑模式选择不同的接口
                const url = this.isEdit ? '/api/admin/template/update' : '/api/admin/template/create';
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(submitData)
                });

                const data = await response.json();
                loadingToast.close();

                if (data.code === 200) {
                    await Swal.fire({
                        icon: 'success',
                        title: this.isEdit ? '更新成功' : '创建成功',
                        showConfirmButton: false,
                        timer: 1500
                    });
                    window.location.href = 'templates.html';
                } else {
                    throw new Error(data.msg || (this.isEdit ? '更新失败' : '创建失败'));
                }
            } catch (error) {
                console.error(this.isEdit ? '更新模板失败:' : '创建模板失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: this.isEdit ? '更新失败' : '创建失败',
                    text: error.message || '请重试'
                });
            }
        },
        async handleBack() {
            // 检查是否有未保存的更改
            if (this.formData.name || 
                this.formData.pictures_count !== 1 || 
                this.formData.sample_data || 
                this.formData.input_fields.length > 0) {
                
                const result = await Swal.fire({
                    title: '确认返回？',
                    text: '有未保存的更改，确定要返回吗？',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: '确定返回',
                    cancelButtonText: '取消',
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6'
                });

                if (!result.isConfirmed) {
                    return;
                }
            }
            
            window.location.href = 'templates.html';
        },
        handlePriceInput(e) {
            // 保持输入框显示的是元为单位的值
            const yuanValue = parseFloat(e.target.value) || 0;
            // 转换为分存储，使用 toFixed(2) 确保精确到分
            this.formData.price = Math.round(yuanValue * 100);
            // 更新输入框的值，确保显示正确的小数位数
            e.target.value = yuanValue.toFixed(2);
        },
        addSwitchReason() {
            // 确保 switch_reasons 是数组
            if (!Array.isArray(this.formData.switch_reasons)) {
                this.formData.switch_reasons = [];
            }
            this.formData.switch_reasons.push({
                text: ''
            });
        },
        removeSwitchReason(index) {
            if (Array.isArray(this.formData.switch_reasons)) {
                this.formData.switch_reasons.splice(index, 1);
            }
        }
    },
    mounted() {
        console.log('Vue instance mounted');
        this.$nextTick(() => {
            this.initEditor();
            this.initTemplate();
            this.loadCategories();
        });
    }
}).mount('#templateAddApp'); 